package cn.kgc.tcst004.controller;



import cn.kgc.tcst004.pojo.Blog;
import cn.kgc.tcst004.service.BlogService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


@Controller
@RequestMapping("/blog")
public class BlogController {
    @Autowired
    private BlogService blogService;

    public BlogService getBlogService() {
        return blogService;
    }

    public void setBlogService(BlogService blogService) {
        this.blogService = blogService;
    }

    @RequestMapping(value = "getBlogs.do",method = RequestMethod.POST)
    public void getBlogs(HttpServletRequest request, HttpServletResponse response){
        int pageIndex = 1;
        int pageSize = 1;
        if (request.getParameter("pageIndex")!=null&&request.getParameter("pageIndex").length()>0) {
            pageIndex=Integer.parseInt(request.getParameter("pageIndex"));
        }
        PageHelper.startPage(pageIndex, pageSize);
        List<Blog> blogs = blogService.getBlogs();
        PageInfo<Blog> pageInfo = new PageInfo<Blog>(blogs);
        try {
            response.getWriter().print(new Gson().toJson(pageInfo));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @RequestMapping(value = "inert.do")
    public String inert(Blog blog, HttpSession session) {
        System.out.println(blog.getId());
        System.out.println(blog.getContent());
        System.out.println("进入添加微博");
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        System.out.println(df.format(new Date()));// new Date()为获取当前系统时间
        String shijian = df.format(new Date());
        blog.setPublishtime(shijian);
        int insert = blogService.insert(blog);
        if (insert > 0) {
            // 添加成功 跳转该页面
            System.out.println("添加微博内容成功");
            return "index";
        } else {
            // 添加失败 跳回添加页面
            return "addBlog";
        }
    }
}

